package com.nph.fireworks.client.mvp;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;


public class AppController implements Presenter, ValueChangeHandler<String> {
	private final EventBus eventBus;
	private HasWidgets container;
	private CountdownView countdownView = null;
	private ConfigView configView = null;
	
	public AppController(EventBus eventBus) {
		this.eventBus = eventBus;
		bind();
	}

	public void bind() {
		History.addValueChangeHandler(this);
	}

	public void go(final HasWidgets container) {
		this.container = container;
		
		if ("".equals(History.getToken())) {
			History.newItem("config");
		} else {
			History.fireCurrentHistoryState();
		}
	}

	public void onValueChange(ValueChangeEvent<String> event) {
		String token = event.getValue();

		if (token != null) {
			if (token.equals("config")) {
				if (configView == null) {
					configView = new ConfigView();
				}
				new ConfigPresenter(eventBus, configView).go(container);
			} else if (token.equals("start")) {
				if (countdownView == null) {
					countdownView = new CountdownView();
				}
				
				new CountdownPresenter(eventBus, countdownView).go(container);
			}
			
		}
	}
}
